<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;

class MenuResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $data = [
            'id' => $this->id,
            'parent_id' => $this->parent_id,
            'title' => $this->title,
            'name' => $this->name,
            'path' => $this->path,
            'component' => $this->component,
            'icon' => $this->icon,
            'type' => $this->type,
            'permission' => $this->permission,
            'status' => $this->status,
            'sort' => $this->sort,
            'hidden' => $this->hidden,
            'keep_alive' => $this->keep_alive,
            'remark' => $this->remark,
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
        
        // 处理parent关系
        if ($this->relationLoaded('parent') && $this->parent) {
            $data['parent'] = [
                'id' => $this->parent->id,
                'title' => $this->parent->title,
            ];
        }
        
        // 处理children：tree()方法现在使用setRelation设置children
        // 所以可以通过relationLoaded检查
        if ($this->relationLoaded('children')) {
            $children = $this->children;
            if ($children instanceof \Illuminate\Database\Eloquent\Collection && $children->isNotEmpty()) {
                // 递归转换为资源集合
                $data['children'] = MenuResource::collection($children)->resolve($request);
            } else {
                $data['children'] = [];
            }
        } else {
            // 如果没有children关系，返回空数组
            $data['children'] = [];
        }
        
        return $data;
    }
}

